const Product = require("../models/products");
const User = require("../models/users");
const { formatSuccess } = require("../utils");

class ProductCtrl {
  // 查询所有
  async find(ctx) {
    const product = await Product.find();
    ctx.body = formatSuccess(product);
  }
  // 查询单个物品
  async findById(ctx) {
    const product = await Product.findById(ctx.params.id).populate("producter");
    if (!product) {
      ctx.throw(404, "产品不存在");
    }
    ctx.body = formatSuccess(product, "产品查询成功");
  }
  // 添加物品
  async create(ctx) {
    ctx.verifyParams({
      title: {
        type: "string",
        required: true,
      },
      description: {
        type: "string",
        required: false,
      },
      price: {
        type: "string",
        required: false,
      },
    });
    const producter = ctx.state.user._id;
    console.log(producter);
    const product = await new Product({
      ...ctx.request.body,
      producter,
    }).save();

    ctx.body = formatSuccess(product);
  }
  // 查询某个用户发布的产品
  async findProductsByUser(ctx){
    const user_id = ctx.params.id
    const user = await User.findById(user_id);
    if (!user) {
      ctx.throw(404, "用户不存在");
    }
    const product = await Product.find();
    const filterList = product.filter(item=>{
      return item.producter = user_id
    })
    ctx.body = filterList
  }
}

module.exports = new ProductCtrl();
